import React, { useState, useEffect } from 'react';
import {
  Card, Table, Button, Space, Tag, Modal, message,
  Popconfirm, Tooltip, Spin, Row, Col, Steps, Alert, Empty
} from 'antd';
import {
  PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined,
  SyncOutlined, CheckCircleOutlined, ExclamationCircleOutlined,
  LoginOutlined, LogoutOutlined, UserOutlined, LoadingOutlined, UserAddOutlined
} from '@ant-design/icons';
import { useAccountStore } from '../stores/accountStore';

const { Step } = Steps;

const Accounts: React.FC = () => {
  const [isLoginModalVisible, setIsLoginModalVisible] = useState(false);
  const [loginStep, setLoginStep] = useState(0);
  const [loginLoading, setLoginLoading] = useState(false);
  const [checkingStatus, setCheckingStatus] = useState(false);

  const {
    accounts, currentAccount, loading, error, fetchAccounts,
    updateAccount, deleteAccount, syncAccount,
    openLoginPage, checkLoginStatus, getLoginInfoAndSave, switchCurrentAccount, logoutAccount
  } = useAccountStore();

  useEffect(() => {
    fetchAccounts();
  }, [fetchAccounts]);

  // 获取状态标签
  const getStatusTag = (status: string) => {
    switch (status) {
      case 'active':
        return <Tag color="green" icon={<CheckCircleOutlined />}>正常</Tag>;
      case 'inactive':
        return <Tag color="orange" icon={<ExclamationCircleOutlined />}>未激活</Tag>;
      case 'error':
        return <Tag color="red" icon={<ExclamationCircleOutlined />}>异常</Tag>;
      default:
        return <Tag color="default">{status}</Tag>;
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '昵称',
      dataIndex: 'nickname',
      key: 'nickname',
      render: (text: string, record: any) => (
        <Space>
          <UserOutlined />
          <span>{text}</span>
          {record.isCurrent && <Tag color="blue">当前</Tag>}
        </Space>
      ),
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => getStatusTag(status),
    },
    {
      title: '粉丝数',
      dataIndex: 'followers',
      key: 'followers',
      render: (value: number) => value.toLocaleString(),
    },
    {
      title: '关注数',
      dataIndex: 'following',
      key: 'following',
      render: (value: number) => value.toLocaleString(),
    },
    {
      title: '发布数',
      dataIndex: 'posts',
      key: 'posts',
      render: (value: number) => value.toLocaleString(),
    },
    {
      title: '最后登录',
      dataIndex: 'lastLogin',
      key: 'lastLogin',
      render: (date: string) => new Date(date).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (text: string, record: any) => (
        <Space size="small">
          {!record.isCurrent && (
            <Button
              size="small"
              icon={<LoginOutlined />}
              onClick={() => handleSwitchAccount(record)}
            >
              切换
            </Button>
          )}
          <Button
            size="small"
            icon={<SyncOutlined />}
            onClick={() => handleSync(record)}
          >
            同步
          </Button>
          <Button
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleReLogin(record)}
          >
            重新登录
          </Button>
          <Popconfirm
            title="确定要删除这个账号吗？"
            onConfirm={() => handleDelete(record)}
            okText="确定"
            cancelText="取消"
          >
            <Button size="small" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 登录步骤定义
  const loginSteps = [
    {
      title: '打开登录页面',
      description: '系统将打开浏览器并跳转到小红书登录页面'
    },
    {
      title: '手动登录',
      description: '请在浏览器中完成登录（手机号+验证码或扫码）'
    },
    {
      title: '获取登录信息',
      description: '系统将自动获取登录信息并保存账号'
    }
  ];

  // 处理新增账号
  const handleAddAccount = () => {
    setLoginStep(0);
    setIsLoginModalVisible(true);
  };

  // 处理重新登录
  const handleReLogin = (account: any) => {
    setLoginStep(0);
    setIsLoginModalVisible(true);
  };

  // 处理删除账号
  const handleDelete = async (account: any) => {
    try {
      await deleteAccount(account.id);
      message.success('删除成功');
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 处理同步数据
  const handleSync = async (account: any) => {
    try {
      await syncAccount(account.id);
      message.success('同步成功');
    } catch (error) {
      message.error('同步失败');
    }
  };

  // 处理切换账号
  const handleSwitchAccount = async (account: any) => {
    try {
      await switchCurrentAccount(account.id);
      message.success('切换成功');
    } catch (error) {
      message.error('切换失败');
    }
  };

  // 打开登录页面
  const handleOpenLoginPage = async () => {
    try {
      setLoginLoading(true);
      const result = await openLoginPage();
      setLoginLoading(false);

      if (result.success) {
        message.success('登录页面已打开，请在浏览器中完成登录');
        setLoginStep(1);
      } else {
        message.error(result.message);
      }
    } catch (error) {
      setLoginLoading(false);
      message.error('打开登录页面失败');
    }
  };

  // 检查登录状态
  const handleCheckLoginStatus = async () => {
    try {
      setCheckingStatus(true);
      const result = await checkLoginStatus();
      setCheckingStatus(false);

      if (result.isLoggedIn) {
        message.success('检测到已登录，正在获取账号信息...');
        setLoginStep(2);
        await handleGetLoginInfo();
      } else {
        message.warning('未检测到登录，请先完成登录');
      }
    } catch (error) {
      setCheckingStatus(false);
      message.error('检查登录状态失败');
    }
  };

  // 获取登录信息
  const handleGetLoginInfo = async () => {
    try {
      setLoginLoading(true);
      const result = await getLoginInfoAndSave();
      setLoginLoading(false);

      if (result.success) {
        message.success('登录成功，账号信息已保存');
        setIsLoginModalVisible(false);
        setLoginStep(0);
        // 刷新账号列表
        await fetchAccounts();
      } else {
        message.error(result.message);
      }
    } catch (error) {
      setLoginLoading(false);
      message.error('获取登录信息失败');
    }
  };

  // 处理模态框取消
  const handleModalCancel = () => {
    setIsLoginModalVisible(false);
    setLoginStep(0);
    setLoginLoading(false);
    setCheckingStatus(false);
  };

  return (
    <div>
      <Card
        title="小红书账号管理"
        extra={
          <Space>
            {currentAccount && (
              <span style={{ color: '#666' }}>
                当前账号: {currentAccount.nickname}
              </span>
            )}
            <Button
              type="primary"
              icon={<UserAddOutlined />}
              onClick={handleAddAccount}
            >
              添加小红书账号
            </Button>
          </Space>
        }
      >
        <Spin spinning={loading}>
          {accounts.length === 0 ? (
            <Empty
              description="暂无小红书账号"
              image={Empty.PRESENTED_IMAGE_SIMPLE}
            >
              <Button type="primary" icon={<UserAddOutlined />} onClick={handleAddAccount}>
                添加第一个账号
              </Button>
            </Empty>
          ) : (
            <Table
              columns={columns}
              dataSource={accounts}
              rowKey="id"
              pagination={{
                total: accounts.length,
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) =>
                  `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
              }}
            />
          )}
        </Spin>
      </Card>

      {/* 登录模态框 */}
      <Modal
        title="添加小红书账号"
        open={isLoginModalVisible}
        onCancel={handleModalCancel}
        width={600}
        footer={null}
      >
        <Steps current={loginStep} style={{ marginBottom: 24 }}>
          {loginSteps.map((step, index) => (
            <Step key={index} title={step.title} description={step.description} />
          ))}
        </Steps>

        <Alert
          message="登录说明"
          description="系统将打开浏览器跳转到小红书登录页面，请手动完成登录。支持手机号+验证码登录或扫码登录。"
          type="info"
          showIcon
          style={{ marginBottom: 16 }}
        />

        <div style={{ textAlign: 'center', padding: '20px 0' }}>
          {loginStep === 0 && (
            <Space direction="vertical" size="large">
              <Button
                type="primary"
                size="large"
                icon={<UserAddOutlined />}
                onClick={handleOpenLoginPage}
                loading={loginLoading}
              >
                打开登录页面
              </Button>
              
              <div style={{ marginTop: 16 }}>
                <p style={{ color: '#666', marginBottom: 8 }}>
                  如果你已经在浏览器中完成了登录，可以点击下方按钮检查状态：
                </p>
                <Button
                  size="large"
                  icon={<LoginOutlined />}
                  onClick={handleCheckLoginStatus}
                  loading={checkingStatus}
                >
                  我已登录，检查状态
                </Button>
              </div>
            </Space>
          )}

          {loginStep === 1 && (
            <Space>
              <Button
                type="primary"
                size="large"
                icon={<LoginOutlined />}
                onClick={handleCheckLoginStatus}
                loading={checkingStatus}
              >
                我已登录，检查状态
              </Button>
              <Button
                size="large"
                onClick={handleOpenLoginPage}
                loading={loginLoading}
              >
                重新打开登录页面
              </Button>
            </Space>
          )}

          {loginStep === 2 && (
            <div>
              <p style={{ marginBottom: 16, color: '#52c41a' }}>
                ✓ 检测到已登录，正在获取账号信息...
              </p>
              <Spin size="large" />
            </div>
          )}
        </div>
      </Modal>
    </div>
  );
};

export default Accounts; 